<!--
  商户表单组件
  @description 商户新增/编辑表单对话框
  @author AI Assistant
  @since 1.0.0
-->
<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="800px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="t('settle.merchant.merchantName')" prop="merchantName">
            <el-input
              v-model="formData.merchantName"
              :placeholder="t('settle.merchant.rules.merchantNameRequired')"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('settle.merchant.merchantType')" prop="merchantType">
            <el-select
              v-model="formData.merchantType"
              :placeholder="t('settle.merchant.rules.merchantTypeRequired')"
              style="width: 100%"
            >
              <el-option
                v-for="(label, value) in merchantTypeOptions"
                :key="value"
                :label="label"
                :value="parseInt(value)"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="t('settle.merchant.channelType')" prop="channelType">
            <el-select
              v-model="formData.channelType"
              :placeholder="t('settle.merchant.rules.channelTypeRequired')"
              style="width: 100%"
            >
              <el-option
                v-for="(label, value) in channelTypeOptions"
                :key="value"
                :label="label"
                :value="parseInt(value)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('settle.merchant.settleCycle')" prop="settleCycle">
            <el-select
              v-model="formData.settleCycle"
              :placeholder="t('settle.merchant.rules.settleCycleRequired')"
              style="width: 100%"
            >
              <el-option
                v-for="(label, value) in settleCycleOptions"
                :key="value"
                :label="label"
                :value="parseInt(value)"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="t('settle.merchant.contactName')" prop="contactName">
            <el-input
              v-model="formData.contactName"
              :placeholder="t('settle.merchant.rules.contactNameRequired')"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('settle.merchant.contactPhone')" prop="contactPhone">
            <el-input
              v-model="formData.contactPhone"
              :placeholder="t('settle.merchant.rules.contactPhoneRequired')"
              maxlength="20"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="t('settle.merchant.contactEmail')" prop="contactEmail">
            <el-input
              v-model="formData.contactEmail"
              :placeholder="t('settle.common.pleaseInput') + t('settle.merchant.contactEmail')"
              maxlength="100"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('settle.merchant.settleAccount')" prop="settleAccount">
            <el-input
              v-model="formData.settleAccount"
              :placeholder="t('settle.merchant.rules.settleAccountRequired')"
              maxlength="50"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item :label="t('settle.common.remark')" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :placeholder="t('settle.common.pleaseInput') + t('settle.common.remark')"
          :rows="3"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">
        {{ t('settle.common.confirm') }}
      </el-button>
      <el-button @click="dialogVisible = false">
        {{ t('settle.common.cancel') }}
      </el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { getMerchantApi, createMerchantApi, updateMerchantApi } from '@/api/settle/merchant'
import type { MerchantVO, MerchantCreateReqVO, MerchantUpdateReqVO } from '@/api/settle/types'
import { MerchantTypeEnum, ChannelTypeEnum, SettleCycleEnum } from '@/api/settle/types'
import { Dialog } from '@/components/Dialog'

defineOptions({ name: 'MerchantForm' })

const { t } = useI18n()

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)

// 表单相关
const formRef = ref<FormInstance>()
const formType = ref('')
const formData = ref<MerchantCreateReqVO>({
  merchantName: '',
  merchantType: MerchantTypeEnum.ENTERPRISE,
  channelType: ChannelTypeEnum.HUIFU,
  contactName: '',
  contactPhone: '',
  contactEmail: '',
  settleCycle: SettleCycleEnum.DAILY,
  settleAccount: '',
  remark: ''
})

// 选项数据
const merchantTypeOptions = {
  [MerchantTypeEnum.ENTERPRISE]: t('settle.merchant.merchantTypes.enterprise'),
  [MerchantTypeEnum.INDIVIDUAL]: t('settle.merchant.merchantTypes.individual'),
  [MerchantTypeEnum.MICRO]: t('settle.merchant.merchantTypes.micro')
}

const channelTypeOptions = {
  [ChannelTypeEnum.HUIFU]: t('settle.merchant.channelTypes.huifu'),
  [ChannelTypeEnum.UNIONPAY]: t('settle.merchant.channelTypes.unionpay')
}

const settleCycleOptions = {
  [SettleCycleEnum.DAILY]: t('settle.merchant.settleCycles.daily'),
  [SettleCycleEnum.WEEKLY]: t('settle.merchant.settleCycles.weekly'),
  [SettleCycleEnum.MONTHLY]: t('settle.merchant.settleCycles.monthly')
}

// 表单校验规则
const formRules = reactive<FormRules>({
  merchantName: [
    { required: true, message: t('settle.merchant.rules.merchantNameRequired'), trigger: 'blur' }
  ],
  merchantType: [
    { required: true, message: t('settle.merchant.rules.merchantTypeRequired'), trigger: 'change' }
  ],
  channelType: [
    { required: true, message: t('settle.merchant.rules.channelTypeRequired'), trigger: 'change' }
  ],
  contactName: [
    { required: true, message: t('settle.merchant.rules.contactNameRequired'), trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: t('settle.merchant.rules.contactPhoneRequired'), trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: t('settle.merchant.rules.contactPhoneFormat'),
      trigger: 'blur'
    }
  ],
  contactEmail: [
    {
      type: 'email',
      message: t('settle.merchant.rules.contactEmailFormat'),
      trigger: 'blur'
    }
  ],
  settleCycle: [
    { required: true, message: t('settle.merchant.rules.settleCycleRequired'), trigger: 'change' }
  ],
  settleAccount: [
    { required: true, message: t('settle.merchant.rules.settleAccountRequired'), trigger: 'blur' }
  ]
})

// 计算属性
const isUpdate = computed(() => formType.value === 'update')

// 事件定义
const emit = defineEmits(['success'])

/**
 * 打开弹窗
 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value =
    type === 'create'
      ? t('settle.common.add') + t('settle.merchant.title')
      : t('settle.common.edit') + t('settle.merchant.title')
  formType.value = type
  resetForm()

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await getMerchantApi(id)
      Object.assign(formData.value, data)
    } catch (error) {
      console.error('获取商户详情失败:', error)
    } finally {
      formLoading.value = false
    }
  }
}

/**
 * 提交表单
 */
const submitForm = async () => {
  const valid = await formRef.value?.validate()
  if (!valid) return

  formLoading.value = true
  try {
    const data = { ...formData.value }
    if (isUpdate.value) {
      await updateMerchantApi(data as MerchantUpdateReqVO)
      ElMessage.success(t('settle.merchant.tips.updateSuccess'))
    } else {
      await createMerchantApi(data)
      ElMessage.success(t('settle.merchant.tips.createSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('保存商户失败:', error)
  } finally {
    formLoading.value = false
  }
}

/**
 * 重置表单
 */
const resetForm = () => {
  formData.value = {
    merchantName: '',
    merchantType: MerchantTypeEnum.ENTERPRISE,
    channelType: ChannelTypeEnum.HUIFU,
    contactName: '',
    contactPhone: '',
    contactEmail: '',
    settleCycle: SettleCycleEnum.DAILY,
    settleAccount: '',
    remark: ''
  }
  formRef.value?.resetFields()
}

// 暴露方法
defineExpose({ open })
</script>
